#!/bin/bash
# SSH代理自动化配置工具（增强版）
# 功能：支持多配置文件、代理模式切换（全局/应用级/关闭）

# ================================== 基础配置 ==================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置文件路径（区分环境）
if [ -n "$TERMUX_VERSION" ]; then
    CONFIG_DIR="$HOME/.ssh_proxy_configs"
    LOG_FILE="$HOME/ssh_proxy.log"
    PROXYCHAINS_CONF="$HOME/.proxychains4.conf"
    PROXYCHAINS_CONF_BAK="$HOME/.proxychains4.conf.bak"
    REDSOCKS_CONF="$HOME/.redsocks.conf"
    REDSOCKS_CONF_BAK="$HOME/.redsocks.conf.bak"
    SUPPORT_GLOBAL_PROXY=0
else
    CONFIG_DIR="$HOME/.ssh_proxy_configs"
    LOG_FILE="$HOME/ssh_proxy.log"
    PROXYCHAINS_CONF="/etc/proxychains4.conf"
    PROXYCHAINS_CONF_BAK="/etc/proxychains4.conf.bak"
    REDSOCKS_CONF="/etc/redsocks.conf"
    REDSOCKS_CONF_BAK="/etc/redsocks.conf.bak"
    SUPPORT_GLOBAL_PROXY=1
fi

# 创建配置目录
mkdir -p "$CONFIG_DIR"
CURRENT_PROFILE="$CONFIG_DIR/current"  # 记录当前使用的配置文件
NO_PACKAGE_MANAGER=0  # 无包管理器标识


# ================================== 工具函数 ==================================
log() {
    local level="$1"
    local message="$2"
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] [$level] $message" | tee -a "$LOG_FILE"
}

check_command() {
    command -v "$1" >/dev/null 2>&1
}

check_root() {
    if [ -z "$TERMUX_VERSION" ] && [ "$(id -u)" -ne 0 ]; then
        log "ERROR" "请使用root权限运行此脚本（Linux环境）"
        echo -e "${RED}错误：需要root权限，请用sudo运行${NC}"
        exit 1
    fi
}

# 显示带颜色的消息
info_msg() {
    echo -e "${BLUE}$1${NC}"
}

success_msg() {
    echo -e "${GREEN}$1${NC}"
}

error_msg() {
    echo -e "${RED}$1${NC}"
}

warning_msg() {
    echo -e "${YELLOW}$1${NC}"
}


# ================================== 依赖编译安装 ==================================
install_from_source() {
    local name="$1"
    local repo="$2"
    local install_dir="${3:-/usr/local}"
    local build_cmd="${4:-make}"
    local install_cmd="${5:-make install}"

    log "INFO" "开始从源码编译安装$name"
    local temp_dir=$(mktemp -d)
    info_msg "正在下载$name源码..."
    if ! git clone --depth 1 "$repo" "$temp_dir"; then
        log "ERROR" "$name源码克隆失败（仓库：$repo）"
        error_msg "错误：$name源码下载失败，请检查网络"
        rm -rf "$temp_dir"
        return 1
    fi

    info_msg "正在编译$name..."
    cd "$temp_dir" || {
        log "ERROR" "进入$name源码目录失败（路径：$temp_dir）"
        rm -rf "$temp_dir"
        return 1
    }

    if ! eval "$build_cmd"; then
        log "ERROR" "$name编译失败（命令：$build_cmd）"
        error_msg "错误：$name编译失败，请查看日志"
        rm -rf "$temp_dir"
        return 1
    fi

    if ! eval "$install_cmd"; then
        log "ERROR" "$name安装失败（命令：$install_cmd）"
        error_msg "错误：$name安装失败，请检查权限"
        rm -rf "$temp_dir"
        return 1
    fi

    cd - >/dev/null || exit
    rm -rf "$temp_dir"
    log "INFO" "$name源码安装成功"
    success_msg "$name安装成功"
    return 0
}

check_package_manager() {
    if ! check_command apt-get && ! check_command yum && ! check_command pacman && ! check_command pkg; then
        NO_PACKAGE_MANAGER=1
        log "INFO" "未检测到任何包管理器，将通过源码编译所有依赖"
    fi
}

install_without_package_manager() {
    local compile_basics="gcc make git"
    local missing_basics=""
    for dep in $compile_basics; do
        if ! check_command "$dep"; then
            missing_basics="$missing_basics $dep"
        fi
    done
    if [ -n "$missing_basics" ]; then
        log "ERROR" "缺少基础编译工具：$missing_basics（无包管理器必需）"
        error_msg "错误：无包管理器环境需先手动安装这些工具：$missing_basics"
        exit 1
    fi

    local deps=(
        "proxychains-ng https://github.com/rofl0r/proxychains-ng.git './configure --prefix=/usr/local' 'make install && make install-config'"
        "redsocks https://github.com/darkk/redsocks.git 'make' 'make install'"
        "lsof https://github.com/lsof-org/lsof.git './Configure -n linux' 'make && make install'"
        "iptables https://git.netfilter.org/iptables.git './configure --prefix=/usr/local' 'make install'"
        "curl https://github.com/curl/curl.git './configure --prefix=/usr/local' 'make install'"
    )

    for dep in "${deps[@]}"; do
        local name=$(echo "$dep" | awk '{print $1}')
        local repo=$(echo "$dep" | awk '{print $2}')
        local build_cmd=$(echo "$dep" | awk -F'\' '{print $2}' | sed "s/'//g")
        local install_cmd=$(echo "$dep" | awk -F'\' '{print $3}' | sed "s/'//g")

        if check_command "$name" || check_command "$(echo $name | sed 's/-ng//')"; then
            log "INFO" "$name已安装，跳过"
            continue
        fi

        if ! install_from_source "$name" "$repo" "/usr/local" "$build_cmd" "$install_cmd"; then
            log "ERROR" "$name安装失败，无包管理器环境无法继续"
            exit 1
        fi
    done

    if ! echo "$PATH" | grep -q "/usr/local/bin"; then
        echo 'export PATH=/usr/local/bin:$PATH' >> "$HOME/.bashrc"
        source "$HOME/.bashrc"
        log "INFO" "已添加/usr/local/bin到PATH"
    fi
}

install_termux_deps() {
    local missing=()
    local base_deps="git make gcc libtool automake curl lsof openssh"
    local tool_deps="proxychains4"

    for dep in $base_deps; do
        if ! check_command "$dep"; then
            missing+=("$dep")
        fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        info_msg "安装Termux基础依赖：${missing[*]}"
        if ! pkg install -y "${missing[@]}"; then
            log "ERROR" "Termux基础依赖安装失败"
            exit 1
        fi
    fi

    if ! check_command "redsocks"; then
        install_from_source "redsocks" "https://github.com/darkk/redsocks.git" || exit 1
    fi
    if ! check_command "proxychains4"; then
        install_from_source "proxychains-ng" "https://github.com/rofl0r/proxychains-ng.git" "./configure --prefix=/usr/local" "make install" || exit 1
    fi
}

install_linux_deps() {
    local missing_deps=$(check_dependencies)
    [ -z "$missing_deps" ] && { log "INFO" "所有依赖已安装"; return 0; }

    log "INFO" "通过包管理器安装缺失依赖：$missing_deps"
    if check_command apt-get; then
        apt-get update >/dev/null 2>&1
        apt-get install -y $missing_deps >/dev/null 2>&1
    elif check_command yum; then
        yum install -y $missing_deps >/dev/null 2>&1
    elif check_command pacman; then
        pacman -Sy --noconfirm $missing_deps >/dev/null 2>&1
    fi

    local compile_deps=()
    for dep in $missing_deps; do
        if ! check_command "$dep"; then
            compile_deps+=("$dep")
        fi
    done
    [ ${#compile_deps[@]} -eq 0 ] && return 0

    for dep in "${compile_deps[@]}"; do
        case $dep in
            redsocks)
                install_from_source "redsocks" "https://github.com/darkk/redsocks.git" || exit 1
                ;;
            proxychains4|proxychains-ng)
                install_from_source "proxychains-ng" "https://github.com/rofl0r/proxychains-ng.git" || exit 1
                ;;
            *)
                log "ERROR" "依赖$dep无法安装，请手动处理"
                exit 1
                ;;
        esac
    done
}

check_dependencies() {
    local missing_dependencies=""
    if check_command apt-get; then
        DEPENDENCIES="proxychains4 redsocks iptables lsof curl"
    elif check_command yum; then
        DEPENDENCIES="openssh-clients proxychains-ng redsocks iptables lsof curl"
    elif check_command pacman; then
        DEPENDENCIES="openssh proxychains-ng redsocks iptables lsof curl"
    fi
    for dep in $DEPENDENCIES; do
        if ! check_command "$dep"; then
            missing_dependencies="$missing_dependencies $dep"
        fi
    done
    echo "$missing_dependencies"
}

install_dependencies() {
    check_package_manager
    if [ "$NO_PACKAGE_MANAGER" -eq 1 ]; then
        install_without_package_manager
    elif [ -n "$TERMUX_VERSION" ]; then
        install_termux_deps
    else
        install_linux_deps
    fi
}


# ================================== 配置文件管理 ==================================
find_available_port() {
    local start_port="$1"
    local end_port="$2"
    local port="$start_port"
    while [ "$port" -le "$end_port" ]; do
        if ! lsof -Pi :$port -sTCP:LISTEN -t >/dev/null; then
            echo "$port"
            return 0
        fi
        ((port++))
    done
    log "ERROR" "端口范围$start_port-$end_port无可用端口"
    error_msg "错误：端口被占用，请手动指定"
    exit 1
}

# 创建新配置文件
create_profile() {
    local profile_name="$1"
    local config_file="$CONFIG_DIR/$profile_name"
    
    if [ -f "$config_file" ]; then
        error_msg "错误：配置文件 '$profile_name' 已存在"
        exit 1
    fi

    info_msg "请输入SSH代理服务器信息（配置文件：$profile_name）"
    read -p "服务器IP地址: " HOST
    read -p "SSH端口(默认22): " PORT
    PORT=${PORT:-22}
    read -p "SSH用户名: " USER

    SSH_SERVER_IP=$(ping -c 1 "$HOST" | grep -oP '(?<=from ).*?(?=:)' | head -n1)
    [ -z "$SSH_SERVER_IP" ] && SSH_SERVER_IP="$HOST"

    PROXY_PORT=$(find_available_port 10000 10100)
    REDSOCKS_PORT=$(find_available_port 10101 10200)
    PROXY_MODE="global"  # 默认全局模式

    save_config "$profile_name" "$HOST" "$PORT" "$USER" "$PROXY_PORT" "$REDSOCKS_PORT" "$SSH_SERVER_IP" "$PROXY_MODE"
    success_msg "配置文件 '$profile_name' 已创建"
    switch_profile "$profile_name"
}

# 保存配置
save_config() {
    local profile_name="$1" host="$2" port="$3" user="$4" proxy_port="$5" redsocks_port="$6" ssh_ip="$7" mode="$8"
    local config_file="$CONFIG_DIR/$profile_name"
    
    cat >"$config_file" <<EOF
HOST=$host
PORT=$port
USER=$user
PROXY_PORT=$proxy_port
REDSOCKS_PORT=$redsocks_port
SSH_SERVER_IP=$ssh_ip
PROXY_MODE=$mode
EOF
    log "INFO" "配置已保存到$config_file"
}

# 加载配置
load_config() {
    local profile_name="$1"
    local config_file="$CONFIG_DIR/$profile_name"
    
    if [ -f "$config_file" ]; then
        source "$config_file"
        log "INFO" "已加载配置: $profile_name ($USER@$HOST:$PORT，代理端口: $PROXY_PORT，模式: $PROXY_MODE)"
        return 0
    else
        log "INFO" "未找到配置文件$config_file"
        return 1
    fi
}

# 切换配置文件
switch_profile() {
    local profile_name="$1"
    local config_file="$CONFIG_DIR/$profile_name"
    
    if [ ! -f "$config_file" ]; then
        error_msg "错误：配置文件 '$profile_name' 不存在"
        exit 1
    fi
    
    echo "$profile_name" > "$CURRENT_PROFILE"
    log "INFO" "已切换到配置文件: $profile_name"
    success_msg "已切换到配置文件: $profile_name"
    
    # 如果代理正在运行，重启以应用新配置
    if is_proxy_running; then
        warning_msg "检测到代理正在运行，将重启以应用新配置..."
        stop_proxy
        start_proxy "$profile_name"
    fi
}

# 列出所有配置文件
list_profiles() {
    info_msg "可用的配置文件："
    local current_profile=$(get_current_profile)
    
    for file in "$CONFIG_DIR"/*; do
        if [ -f "$file" ] && [ "$file" != "$CURRENT_PROFILE" ]; then
            local profile_name=$(basename "$file")
            if [ "$profile_name" == "$current_profile" ]; then
                echo -e "  * $profile_name (当前使用)"
            else
                echo -e "    $profile_name"
            fi
        fi
    done
    
    if [ -z "$(ls -A "$CONFIG_DIR" 2>/dev/null)" ] || [ $(ls -1qA "$CONFIG_DIR" | wc -l) -eq 0 ]; then
        warning_msg "  没有配置文件，请使用 'create' 命令创建"
    fi
}

# 删除配置文件
delete_profile() {
    local profile_name="$1"
    local config_file="$CONFIG_DIR/$profile_name"
    local current_profile=$(get_current_profile)
    
    if [ ! -f "$config_file" ]; then
        error_msg "错误：配置文件 '$profile_name' 不存在"
        exit 1
    fi
    
    if [ "$profile_name" == "$current_profile" ]; then
        warning_msg "正在删除当前使用的配置文件，将停止代理"
        stop_proxy
        rm -f "$CURRENT_PROFILE"
    fi
    
    rm -f "$config_file"
    log "INFO" "已删除配置文件: $profile_name"
    success_msg "已删除配置文件: $profile_name"
}

# 获取当前配置文件
get_current_profile() {
    if [ -f "$CURRENT_PROFILE" ]; then
        cat "$CURRENT_PROFILE"
        return 0
    else
        return 1
    fi
}


# ================================== 代理模式管理 ==================================
# 切换代理模式
switch_mode() {
    local mode="$1"
    local current_profile=$(get_current_profile)
    
    if [ -z "$current_profile" ]; then
        error_msg "错误：没有当前使用的配置文件，请先创建或切换配置文件"
        exit 1
    fi
    
    if [ "$mode" != "global" ] && [ "$mode" != "app" ] && [ "$mode" != "off" ]; then
        error_msg "错误：无效的模式 '$mode'，支持的模式：global（全局）、app（应用级）、off（关闭）"
        exit 1
    fi
    
    # 如果模式是关闭，直接停止代理
    if [ "$mode" == "off" ]; then
        stop_proxy
        return 0
    fi
    
    # 更新配置文件中的模式
    sed -i "s/^PROXY_MODE=.*/PROXY_MODE=$mode/" "$CONFIG_DIR/$current_profile"
    log "INFO" "已切换代理模式为: $mode"
    success_msg "已切换代理模式为: $mode"
    
    # 重新加载配置并重启代理
    load_config "$current_profile"
    if is_proxy_running; then
        stop_proxy
    fi
    start_proxy "$current_profile"
}

# 显示当前代理状态
show_status() {
    local current_profile=$(get_current_profile)
    
    info_msg "当前代理状态："
    if [ -z "$current_profile" ]; then
        warning_msg "  未选择配置文件"
    else
        echo "  当前配置文件: $current_profile"
        if load_config "$current_profile"; then
            echo "  服务器: $USER@$HOST:$PORT"
            echo "  代理端口: $PROXY_PORT"
            echo "  当前模式: $PROXY_MODE"
            
            if is_proxy_running; then
                success_msg "  代理状态: 运行中"
            else
                warning_msg "  代理状态: 已停止"
            fi
        fi
    fi
}

# 检查代理是否正在运行
is_proxy_running() {
    local current_profile=$(get_current_profile)
    if [ -z "$current_profile" ]; then
        return 1
    fi
    
    if load_config "$current_profile" && ss -ltn | grep -q ":$PROXY_PORT"; then
        return 0
    else
        return 1
    fi
}


# ================================== 代理配置 ==================================
configure_proxychains() {
    local proxy_port="$1"
    log "INFO" "配置proxychains（端口$proxy_port）"

    local conf_path="$PROXYCHAINS_CONF"
    if [ -n "$TERMUX_VERSION" ] && [ ! -f "$conf_path" ]; then
        mkdir -p "$HOME/.config"
        conf_path="$HOME/.proxychains4.conf"
        cp /usr/local/etc/proxychains.conf "$conf_path"
    fi

    if [ ! -f "$PROXYCHAINS_CONF_BAK" ]; then
        cp "$conf_path" "$PROXYCHAINS_CONF_BAK"
        log "INFO" "已备份proxychains配置"
    fi

    cat >"$conf_path" <<EOF
strict_chain
proxy_dns
remote_dns_subnet 224
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5  127.0.0.1 $proxy_port
EOF
}

configure_redsocks() {
    local proxy_port="$1"
    local redsocks_port="$2"
    log "INFO" "配置redsocks（转发到$proxy_port）"

    if [ ! -f "$REDSOCKS_CONF_BAK" ]; then
        cp "$REDSOCKS_CONF" "$REDSOCKS_CONF_BAK" 2>/dev/null || true
        log "INFO" "已备份redsocks配置"
    fi

    cat >"$REDSOCKS_CONF" <<EOF
base {
    log_info = on;
    log = "file:/var/log/redsocks.log";
    daemon = on;
    user = redsocks;
    group = redsocks;
    redirector = iptables;
}
redsocks {
    local_ip = 127.0.0.1;
    local_port = $redsocks_port;
    ip = 127.0.0.1;
    port = $proxy_port;
    type = socks5;
}
EOF
}

configure_system_proxy() {
    local proxy_port="$1"
    log "INFO" "配置系统代理环境变量"
    export http_proxy="socks5h://127.0.0.1:$proxy_port"
    export https_proxy="socks5h://127.0.0.1:$proxy_port"
    export all_proxy="socks5h://127.0.0.1:$proxy_port"
    export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"

    cat >"$HOME/.proxyrc" <<EOF
export http_proxy="socks5h://127.0.0.1:$proxy_port"
export https_proxy="socks5h://127.0.0.1:$proxy_port"
export all_proxy="socks5h://127.0.0.1:$proxy_port"
export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
EOF
}

clear_system_proxy() {
    log "INFO" "清除系统代理环境变量"
    unset http_proxy https_proxy all_proxy no_proxy
    [ -f "$HOME/.proxyrc" ] && rm -f "$HOME/.proxyrc"
}

configure_iptables() {
    local redsocks_port="$1"
    log "INFO" "配置iptables规则（转发到$redsocks_port）"

    iptables -t nat -N REDSOCKS 2>/dev/null
    iptables -t nat -N REDSOCKS2 2>/dev/null
    iptables -t nat -F REDSOCKS
    iptables -t nat -F REDSOCKS2

    local private_nets="0.0.0.0/8 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4"
    for net in $private_nets; do
        iptables -t nat -A REDSOCKS -d "$net" -j RETURN
    done

    [ -n "$SSH_SERVER_IP" ] && iptables -t nat -A REDSOCKS -d "$SSH_SERVER_IP" -j RETURN

    iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports "$redsocks_port"
    iptables -t nat -A REDSOCKS2 -p tcp -m owner --uid-owner proxy -j RETURN
    iptables -t nat -A REDSOCKS2 -p tcp -m owner --gid-owner proxy -j RETURN
    iptables -t nat -A REDSOCKS2 -j REDSOCKS
    iptables -t nat -A OUTPUT -p tcp -j REDSOCKS2 2>/dev/null
    iptables -t nat -A PREROUTING -p tcp -j REDSOCKS 2>/dev/null

    log "INFO" "iptables规则配置完成"
}

clear_iptables() {
    log "INFO" "清除iptables规则"
    iptables -t nat -F REDSOCKS 2>/dev/null
    iptables -t nat -F REDSOCKS2 2>/dev/null
    iptables -t nat -X REDSOCKS 2>/dev/null
    iptables -t nat -X REDSOCKS2 2>/dev/null
    iptables -t nat -D OUTPUT -p tcp -j REDSOCKS2 2>/dev/null
    iptables -t nat -D PREROUTING -p tcp -j REDSOCKS 2>/dev/null
}


# ================================== 服务启停 ==================================
start_tunnel() {
    local host="$1" port="$2" user="$3" proxy_port="$4"
    log "INFO" "启动SSH隧道: $user@$host:$port（本地端口$proxy_port）"

    if ss -ltn | grep -q ":$proxy_port"; then
        log "INFO" "SSH隧道已运行（端口$proxy_port）"
        return 0
    fi

    ssh -fNTD "$proxy_port" "$user@$host" -p "$port" 2>>"$LOG_FILE"
    if [ $? -ne 0 ]; then
        log "ERROR" "SSH隧道启动失败（认证/网络问题）"
        error_msg "错误：SSH连接失败，请检查服务器信息"
        warning_msg "提示：手动测试：ssh -vNT $user@$host -p $port"
        exit 1
    fi

    local wait=0
    while [ "$wait" -lt 5 ]; do
        if ss -ltn | grep -q ":$proxy_port"; then
            log "INFO" "SSH隧道启动成功"
            success_msg "SSH隧道启动成功！"
            return 0
        fi
        sleep 1
        ((wait++))
    done

    log "ERROR" "SSH隧道未监听端口$proxy_port"
    error_msg "错误：SSH隧道启动失败"
    exit 1
}

stop_tunnel() {
    local proxy_port="$1"
    log "INFO" "停止SSH隧道（端口$proxy_port）"
    local pids=$(lsof -i :$proxy_port -sTCP:LISTEN -t)
    if [ -n "$pids" ]; then
        kill -TERM $pids >/dev/null 2>&1
        sleep 2
        if lsof -i :$proxy_port -sTCP:LISTEN -t >/dev/null; then
            kill -KILL $pids >/dev/null 2>&1
            log "WARNING" "强制终止SSH隧道进程"
        fi
        log "INFO" "SSH隧道已停止"
    else
        log "INFO" "无运行中的SSH隧道（端口$proxy_port）"
    fi
}

start_redsocks() {
    local redsocks_port="$1"
    log "INFO" "启动redsocks（端口$redsocks_port）"
    if pgrep -f "redsocks -c $REDSOCKS_CONF" >/dev/null; then
        log "INFO" "redsocks已运行"
        return 0
    fi
    redsocks -c "$REDSOCKS_CONF" >/dev/null 2>&1
    if ! pgrep -f "redsocks -c $REDSOCKS_CONF" >/dev/null; then
        log "ERROR" "redsocks启动失败"
        error_msg "错误：redsocks启动失败"
        exit 1
    fi
    log "INFO" "redsocks启动成功"
}

stop_redsocks() {
    log "INFO" "停止redsocks"
    local pids=$(pgrep -f "redsocks -c $REDSOCKS_CONF")
    if [ -n "$pids" ]; then
        kill $pids >/dev/null 2>&1
        log "INFO" "redsocks已停止"
    else
        log "INFO" "无运行中的redsocks"
    fi
}


# ================================== 代理控制 ==================================
start_proxy() {
    local profile_name="$1"
    
    if [ -z "$profile_name" ]; then
        profile_name=$(get_current_profile)
        if [ -z "$profile_name" ]; then
            error_msg "错误：请指定配置文件或先切换到一个配置文件"
            exit 1
        fi
    fi
    
    install_dependencies
    if ! load_config "$profile_name"; then
        error_msg "错误：配置文件 '$profile_name' 不存在"
        exit 1
    fi
    
    # 启动SSH隧道
    start_tunnel "$HOST" "$PORT" "$USER" "$PROXY_PORT"
    
    # 根据模式配置代理
    case "$PROXY_MODE" in
        global)
            start_global_proxy "$PROXY_PORT" "$REDSOCKS_PORT"
            ;;
        app)
            start_app_proxy "$PROXY_PORT"
            ;;
        *)
            error_msg "错误：未知的代理模式 '$PROXY_MODE'"
            exit 1
            ;;
    esac
    
    # 测试代理
    test_proxy "$PROXY_PORT" "$PROXY_MODE"
}

stop_proxy() {
    local current_profile=$(get_current_profile)
    
    if [ -n "$current_profile" ] && load_config "$current_profile"; then
        stop_tunnel "$PROXY_PORT"
        stop_redsocks
        [ "$SUPPORT_GLOBAL_PROXY" -eq 1 ] && clear_iptables
        clear_system_proxy
        log "INFO" "代理已停止"
        success_msg "代理已停止，规则已清理"
    else
        log "INFO" "无配置文件，清理残留进程"
        stop_redsocks
        clear_iptables
        clear_system_proxy
        warning_msg "已清理残留，未找到配置文件"
    fi
}

start_global_proxy() {
    local proxy_port="$1" redsocks_port="$2"
    log "INFO" "启动全局代理模式"
    configure_system_proxy "$proxy_port"
    configure_redsocks "$proxy_port" "$redsocks_port"
    start_redsocks "$redsocks_port"
    [ "$SUPPORT_GLOBAL_PROXY" -eq 1 ] && configure_iptables "$redsocks_port"
}

start_app_proxy() {
    local proxy_port="$1"
    log "INFO" "启动应用级代理模式"
    configure_proxychains "$proxy_port"
    clear_system_proxy  # 确保不使用全局环境变量
    stop_redsocks       # 关闭全局代理相关服务
    clear_iptables      # 清除iptables规则
}

test_proxy() {
    local proxy_port="$1" proxy_mode="$2"
    log "INFO" "测试代理连接（模式：$proxy_mode）"
    local test_urls=("https://ipinfo.io/ip" "https://icanhazip.com" "https://ifconfig.me")
    local result=""
    info_msg "测试$proxy_mode代理连接..."

    if [ "$proxy_mode" = "global" ] && [ "$SUPPORT_GLOBAL_PROXY" -eq 1 ]; then
        for url in "${test_urls[@]}"; do
            result=$(curl -s --connect-timeout 5 "$url")
            [ -n "$result" ] && break
        done
    else
        for url in "${test_urls[@]}"; do
            result=$(proxychains4 curl -s --connect-timeout 5 "$url")
            [ -n "$result" ] && break
        done
    fi

    if [ -z "$result" ]; then
        log "ERROR" "代理测试失败"
        error_msg "错误：代理连接失败"
        # 不退出，允许用户排查问题
    else
        log "INFO" "代理测试成功，当前IP：$result"
        success_msg "代理测试成功！当前IP：$result"
    fi
}


# ================================== 帮助与主逻辑 ==================================
show_help() {
    echo -e "${BLUE}SSH代理自动化配置工具（增强版）${NC}"
    echo "功能：支持多配置文件、代理模式切换（全局/应用级/关闭）"
    echo "支持环境：Linux、Termux"
    echo "使用方法："
    echo "  Linux：sudo ./ssh_proxy.sh [命令] [参数]"
    echo "  Termux：./ssh_proxy.sh [命令] [参数]"
    echo "命令列表："
    echo "  配置文件管理："
    echo "    create <名称>   - 创建新的代理配置文件"
    echo "    list            - 列出所有配置文件"
    echo "    switch <名称>   - 切换到指定配置文件"
    echo "    delete <名称>   - 删除指定配置文件"
    echo ""
    echo "  代理控制："
    echo "    start [名称]    - 启动代理（可选指定配置文件）"
    echo "    stop            - 停止代理并清理规则"
    echo "    restart         - 重启当前代理"
    echo "    test            - 测试当前代理连通性"
    echo ""
    echo "  模式管理："
    echo "    mode global     - 切换到全局代理模式（所有流量走代理）"
    echo "    mode app        - 切换到应用级代理（需用proxychains启动应用）"
    echo "    mode off        - 关闭代理"
    echo ""
    echo "  其他："
    echo "    status          - 显示当前代理状态"
    echo "    help            - 显示帮助信息"
    echo ""
    echo "应用级代理使用示例：proxychains4 curl https://example.com"
}

main() {
    check_root
    
    case "$1" in
        # 配置文件管理
        create)
            if [ -z "$2" ]; then
                error_msg "错误：请指定配置文件名称"
                echo "用法：$0 create <配置文件名称>"
                exit 1
            fi
            create_profile "$2"
            ;;
            
        list)
            list_profiles
            ;;
            
        switch)
            if [ -z "$2" ]; then
                error_msg "错误：请指定要切换到的配置文件名称"
                echo "用法：$0 switch <配置文件名称>"
                exit 1
            fi
            switch_profile "$2"
            ;;
            
        delete)
            if [ -z "$2" ]; then
                error_msg "错误：请指定要删除的配置文件名称"
                echo "用法：$0 delete <配置文件名称>"
                exit 1
            fi
            delete_profile "$2"
            ;;
        
        # 代理控制
        start)
            start_proxy "$2"
            ;;
            
        stop)
            stop_proxy
            ;;
            
        restart)
            stop_proxy
            start_proxy
            ;;
            
        test)
            local current_profile=$(get_current_profile)
            if [ -z "$current_profile" ] || ! load_config "$current_profile"; then
                error_msg "错误：请先创建并切换到一个配置文件"
                exit 1
            fi
            test_proxy "$PROXY_PORT" "$PROXY_MODE"
            ;;
        
        # 模式管理
        mode)
            if [ -z "$2" ]; then
                error_msg "错误：请指定代理模式"
                echo "用法：$0 mode <global|app|off>"
                exit 1
            fi
            switch_mode "$2"
            ;;
            
        # 其他
        status)
            show_status
            ;;
            
        help|*)
            show_help
            ;;
    esac
}

main "$@"
